<?php
class ToolbarWidget extends CWidget
{
    public $visible=true;
    public $editMode=false;
    
    protected $moduleMenus = array();
    protected $contentTypeMenus = array();
    
    public function init()
    {
        if (Yii::app()->cmsManager->workflow['type'] == Workflow::TYPE_FINAL)
        {
            $this->visible = false;
        }
        parent::init();
    }
    
    public function run()
    {
        if ($this->visible === false)
        {
            return;
        }
        
        $currentFormat = Yii::app()->urlManager->getUrlFormat();
        Yii::app()->urlManager->setUrlFormat(CUrlManager::GET_FORMAT);
        $themeUrl = Yii::app()->themeManager->baseUrl.'/Admin';
        if ($this->isEditMode())
        {
            $pages = FSM::_run('Cms.page.getParents')->parents;
            $dropDownPages = CHtml::dropDownList('goto_page', $this->controller->pageId, $pages);
            $gotoPageUrl = $this->controller->createUrl('/Core/service/ajax', array('SID'=>'Cms.page.getUrl', 'workflow_id'=>Yii::app()->cmsManager->workflow['id']));
            Yii::app()->clientScript->registerScript('GotoPage', "
var old_page_id = $('.edit-mode .goto-page select').val();
$('.edit-mode .goto-page select').change(function(){
    var _this=this,id = $(this).val();
    var force = ".CJavaScript::encode((int) Yii::app()->request->getQuery('revision', 0)).";
    $.ajax({async: false, url:'{$gotoPageUrl}', data: {page_id:id, force : force}, success: function(data){
        data = eval(data);
        if (data.url != undefined && data.url.length)
        {
            old_page_id = id;
            window.location = data.url;
        }
        else
        {
            var page = $('option[value=\"'+id+'\"]', _this).text().replace(/^\-+/, '');
            $(_this).val(old_page_id);
            alert('Page \"'+page+'\" not active in current workflow.');
        }
    }});
});
            ");
            
            $items = array(
                array('label'=>CHtml::image($themeUrl.'/images/toolbar/save.png', 'Save').'<p>Save</p>', 'url'=>'#', 'itemOptions'=>array('class'=>'save')),
                array('label'=>CHtml::image($themeUrl.'/images/toolbar/new_revision.png', 'New Revision').'<p>New Revision</p>', 'url'=>'#', array('class'=>'new-revision'), 'itemOptions'=>array('class'=>'new')),
                array('label'=>CHtml::image($themeUrl.'/images/toolbar/cancel.png', 'Cancel').'<p>Cancel</p>', 'url'=>'#', 'itemOptions'=>array('class'=>'cancel')),
                array('label'=>CHtml::image($themeUrl.'/images/toolbar/copy.png', 'Copy').'<p>Copy</p>', 'url'=>array('/Cms/admin/page/copyRevision')),
//                array('label'=>'Properties', 'url'=>array('/Cms/admin/page/update', 'id'=>$this->controller->pageId)),
                array('label'=>CHtml::image($themeUrl.'/images/toolbar/template.png', 'Template').'<p>Template</p>', 'url'=>array('/Cms/admin/pageRevision/template',
                    'page_id'=>$this->controller->pageId,
                    'revision_id'=>$this->controller->pageRevision
                ), array('class'=>'template')),
                array('label'=>CHtml::image($themeUrl.'/images/toolbar/properties.png', 'Properties').'<p>Properties</p>', 'url'=>array('/Cms/admin/page/update', 'id'=>$this->controller->pageId)),
                array('label'=>CHtml::image($themeUrl.'/images/toolbar/manage_urls.png', 'Manage Urls').'<p>Manage Urls</p>', 'url'=>array('/Cms/admin/page/url', 'page_id'=>$this->controller->pageId)),
                array('label'=>CHtml::image($themeUrl.'/images/toolbar/revisions.png', 'Revisions').'<p>Revisions</p>', 'url'=>array('/Cms/admin/pageRevision/admin', 'page_id'=>$this->controller->pageId), array('class'=>'revisions')),
                array('label'=>CHtml::image($themeUrl.'/images/toolbar/permissions.png', 'Permissions').'<p>Permissions</p>', 'url'=>'#', array('class'=>'permissions')),
                array('label'=>CHtml::image($themeUrl.'/images/toolbar/header-footer.png', 'Header & Footer').'<p>Header &amp; Footer</p>', 'url'=>array('/Cms/admin/pageWidget/hiddenContainer',
                    'type'=>'header',
                    'page_id'=>$this->controller->pageId,
                    'revision_id'=>$this->controller->pageRevision
                )),
                array('label'=>CHtml::image($themeUrl.'/images/toolbar/exit_edit.png', 'View Page').'<p>View Page</p>', 'url'=>array('/Core/service/ajax', 'SID'=>'Cms.page.editMode'), 'linkOptions'=>array('class'=>'change-mode disabled')),
                array('label'=>'', 'template'=>$dropDownPages, 'url'=>'', 'itemOptions'=>array('class'=>'goto-page')),
            );
        }
        else
        {
            $this->buildModuleMenus();
            $items = array(
                array('label'=>'Dashboard', 'url'=>'#',
                    'items'=>array(
                        array('label'=>'My Sites', 'url'=>'#',
							'items'=>array(
								array('label'=>'<span><!-- Sites --></span>','url'=>'#',
									'items'=>$this->getSiteMenus(),
								),
							),
						),
                        array('label'=>'Sitemap', 'url'=>url('Cms/admin/page/tree', array('layout'=>'popup'))),
                        /*array('label'=>'Looks &amp; Feels', 'url'=>'/Admin/admin/theme/admin',
                            'items'=>array(
                                array('label'=>'<span>Active Theme</span>','url'=>'#',
                                    'items'=>array(
                                        array('label'=>'Templates','url'=>url('Cms/admin/template/admin',array('layout' => 'popup'))),
                                        array('label'=>'Files','url'=>'#'),
                                    ),
                                ),
                                array('label'=>'<span>Themes</span>','url'=>'#',
                                    'items'=>array(
                                        array('label'=>'Browse','url'=>'/Admin/admin/theme/admin'),
                                        array('label'=>'Upload My Theme','url'=>'#'),
                                    ),
                                ),                            
                            ),
                        ),
                        array('label'=>'Statistics', 'url'=>'#'),
                        array('label'=>'Help', 'url'=>'#'),
                        */
                    ),
                    'htmlOptions'=>array(
                        'class'=>'submenu'
                    ),
                    'active'=>true,
                ),
                array('label'=>'Page', 'url'=>'#',
                    'items'=>array(
                        array('label'=>'Content', 'url'=>array('/Core/service/ajax', 'SID'=>'Cms.page.editMode'), 'linkOptions'=>array('class'=>'change-mode disabled')),
                        array('label'=>'Copy', 'url'=>'#'),
                        array('label'=>'New Revision', 'url'=>'#'),
                        array('label'=>'Workflow', 'url'=>array('/Cms/admin/pageRevision/workflow', 'page_id'=>$this->controller->pageId)),
                    ),
                    'htmlOptions'=>array(
                        'class'=>'submenu'
                    )
                ),
               /* array('label'=>'Content', 'url'=>'#',
                    'items'=>array(
                        array('label'=>'Add', 'url'=>'#', 'items' => array(
                            array('label' =>'<span></span>','url'=>'#','items' => $this->getContentTypeMenus('add'))
                        )),
                        array('label'=>'Find', 'url'=>'#', 'items' => array(
                            array('label' =>'<span></span>','url'=>'#','items' => $this->getContentTypeMenus('find'))
                        )),
                        array('label'=>'Files', 'url'=>array('/Admin/tools/fileManager')),
                        array('label'=>'Media', 'url'=>'#'),
                        array('label'=>'Content Types', 'url'=>array('/Cms/admin/contentType/admin')),
                        array('label'=>'New Form', 'url'=>array('/Cms/admin/widget/editForm')),
                    ),
                    'htmlOptions'=>array(
                        'class'=>'submenu'
                    )
                ),*/
                array('label'=>'Users', 'url'=>'#',
                    'items'=>array(
                        array('label'=>'Site Users', 'url'=>array('/User/account/admin')),
                        array('label'=>'Site Management Team', 'url'=>'#'),
                        array('label'=>'Permissions', 'url'=>'#'),
                    ),
                    'htmlOptions'=>array(
                        'class'=>'submenu'
                    )
                ),
                 /*array('label'=>'Modules', 'url'=>'#',
                    'items'=>$this->moduleMenus,
                    'htmlOptions'=>array(
                        'class'=>'submenu'
                    )
                ),
               array('label'=>'Extensions', 'url'=>'#',
                    'items'=>array(
                        array('label'=>'Modules', 'url'=>'/Admin/extensions/module/index'),
                        array('label'=>'Widgets', 'url'=>'#'),
                        array('label'=>'Plugins', 'url'=>'#'),
                        array('label'=>'Extensions', 'url'=>'#'),
                    ),
                    'htmlOptions'=>array(
                        'class'=>'submenu'
                    )
                ),
                array('label'=>CHtml::encode('Settings & Tools'), 'url'=>'#',
                    'items'=>array(
                        array('label'=>'Parameters', 'url'=>array('/Admin/setting')),
                        array('label'=>'Categorization', 'url'=>array('/Admin/term/index','layout' => 'popup')),
                        array('label'=>'Clear Cache', 'url'=>'#'),
                        array('label'=>'Backup', 'url'=>'#'),
                        array('label'=>'Restore', 'url'=>'#'),
                    ),
                    'htmlOptions'=>array(
                        'class'=>'submenu'
                    )
                ),*/
                array('label'=>CHtml::encode('Back Office'), 'url'=>array('/Admin'),
                    'items'=>array(
                        array('label'=>'', 'url'=>'#'),
                    ),
                    'htmlOptions'=>array(
                        'class'=>'submenu'
                    ),
                    'linkOptions' => array(
                        'class' => 'lnk-open-new-window'
                    )
                ),
            );
        }
        
        $this->render('toolbar', array('items'=>$items));
        Yii::app()->urlManager->setUrlFormat($currentFormat);
    }
    
    protected function buildModuleMenus(){
        $dbModules = Module::model()->findAll("is_system = FALSE AND enabled = TRUE");
        foreach ($dbModules as $key => $dbModule) {
            $module = Yii::app()->getModule($dbModule->name);
            if (! method_exists($module, 'getMenus')) continue;
            $menus = $module->getMenus();
            if (count($menus))
            {
                $topLevel = array('label' => $dbModule->friendly_name, 'url' => '#', 'items' => array());
                foreach ($menus as $subMenu)
                {
                    if (isset($subMenu['items']) && is_array($subMenu['items']) && count($subMenu['items']))
                    {
                        $group = '<span style="dislay:none;"></span>';
                        if (isset($subMenu['title']))
                            $group = "<span>{$subMenu['title']}</span>";
                        // remove description
                        foreach($subMenu['items'] as &$item)
                        {
                            if (isset($item['label']) && $item['label'] != '')
                            {
                                $i = strpos($item['label'],'|');
                                if ($i!==false)
                                    $item['label'] = substr($item['label'],0,$i);
                            }    
                        }
                        // add to array items
                        $topLevel['items'][] = array(
                            'label' => $group,
                            'url' => '#',
                            'items' => $subMenu['items'],
                        );
                    }
                }
                $this->moduleMenus[] = $topLevel;
            }
        }  
    }
    
    protected function getContentTypeMenus($action = 'add') {
        if (count($this->contentTypeMenus) == 0) {
            $criteria = new CDbCriteria();
            $criteria->condition = "model NOT iLIKE 'Cms.models.%'";
            $criteria->order = 'name';
            
            $contentTypes = ContentType::model()->findAll($criteria);
            foreach((array)$contentTypes as $type) {
                $this->contentTypeMenus[] = array('label' => $type->name, 'url' => '', 'model' => $type->model);
            }                                        
        }
        
        foreach($this->contentTypeMenus as & $menu) {
            if ($action == 'add')
                $menu['url'] = url('/'.str_replace('.models.','/admin/',$menu['model']).'/update');
            elseif ($action == 'find')
                $menu['url'] = url('/'.str_replace('.models.','/admin/',$menu['model']).'/admin');
        }
        
        return $this->contentTypeMenus;
    }
    
    protected function getSiteMenus() {
        $sites = Site::model()->findAll();
        
        $tld = parse_url(Yii::app()->request->getHostInfo(), PHP_URL_HOST);
        $tld = preg_replace('/.*\.admin\./','',$tld);
        
        $menus = array();
        foreach($sites as $site) {
            $menus[] = array('label' => $site->name, 'url' => "http://{$site->subdomain}.admin.{$tld}");
        }
        return $menus;
    }

    
    protected function isEditMode()
    {
        return Yii::app()->session['editMode'];
    }
}
